<template>
  <div>
    <van-nav-bar title="账号登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符' },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' },
        ]"
      />
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
    <p></p>
    <p class="reg">
      <span>好没有账号，去注册~</span>
    </p>
    <!-- <router-link >好没有账号，去注册~</router-link> -->
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: 'VueLogin',

  data () {
    return {
      username: '',
      password: ''
    }
  },

  mounted () {},

  methods: {

    onClickLeft () {
      this.$router.push('/home/user')
    },
    async onSubmit (values) {
      try {
        const res = await request({
          method: 'post',
          url: '/user/login',
          data: values
        })
        // console.log(res.status)
        if (res.status === 200) {
          // 登录成功
          this.$toast.success({
            message: res.description,
            duration: 400
          })
        } else {
        // 登录失败
          this.$toast.fail({
            message: res.description,
            duration: 400
          })
        }
        localStorage.setItem('token', res.body.token)
        // 延迟600毫秒跳转
        setTimeout(() => {
          this.onClickLeft()
        }, 600)
      } catch (error) {
        console.dir(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.reg {
  text-align: center;
}
</style>
